package com.xiaochong.tir.apiservice.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xc.logclient.utils.LogTrace;
import com.xiaochong.service.common.config.redis.RedisServer;
import com.xiaochong.tir.apiservice.component.HbaseBaseQueryComponent;
import com.xiaochong.tir.apiservice.component.RedisCacheComponent;
import com.xiaochong.tir.common.data.hbasepo.TradesHistory;
import com.xiaochong.tir.common.data.mapper.ExchangeInfoMapper;
import com.xiaochong.tir.common.data.mapper.ExchangeTransactionpairMiddleMapper;
import com.xiaochong.tir.common.data.mapper.KLineTitleMapper;
import com.xiaochong.tir.common.data.mapper.PurchaseOrderMapper;
import com.xiaochong.tir.common.data.mapperSearchResult.ExchangeTransactionpair;
import com.xiaochong.tir.common.data.po.*;
import com.xiaochong.tir.common.data.redisPo.KActionTotalPo;
import com.xiaochong.tir.common.data.vo.*;
import com.xiaochong.tir.common.util.ApiResultCodeUtils;
import com.xiaochong.tir.common.util.DateUtils;
import com.xiaochong.tir.common.util.RedisKeysUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.MathContext;
import java.time.LocalDateTime;
import java.util.*;

/**
 * Created by org on 2018/6/27.
 */
@Service("kLineTradesService")
public class KLineTradesService {
    @Autowired
    private RedisServer rediscConfig ;
    @Autowired
    private HbaseBaseQueryComponent hbaseBaseQueryComponent;

    @Autowired
    private PurchaseOrderMapper purchaseOrderMapper;
    @Autowired
    private KLineTitleMapper kLineTitleMapper;
    @Autowired
    private ExchangeTransactionpairMiddleMapper exchangeTransactionpairMiddleMapper;
    @Autowired
    private ExchangeInfoMapper exchangeInfoMapper;
    @Autowired
    private RedisCacheComponent redisCacheComponent;
    /**
     * 根据实体获取k线行情数据
     * @param query
     * @return
     */
    public List<ApiKActionQuantizationVo> getKLineQuantizationExchange(ExchangeTransactionpairMiddle query) throws Exception{
        long st = System.currentTimeMillis();
        List<ApiKActionQuantizationVo> dataVo = new ArrayList<>();
        //获取所有货币,组装每个需要诊断数据放到redis中
        List<ExchangeTransactionpair> middleList = exchangeTransactionpairMiddleMapper.selectByEntityListOfKLine(query);
        if(middleList == null || middleList.size() == 0){
            return null;
        }
        Integer queryExchange = query.getExchangeId()!=null?query.getExchangeId():0;
        KActionTotalPo kActionTotalPo;
        String data;
        LocalDateTime time = LocalDateTime.now();
        Map<String,ApiCapitalInflowSituationVo> flowMap;
        ApiCapitalInflowSituationVo today ;
        String redisKey;
        String redisPriceDate = DateUtils.localDateTimeFormatString(time,DateUtils.format_ymds);
        ApiKActionQuantizationVo vo;
        //long ss = System.currentTimeMillis();
        BigDecimal lastPriceB = new BigDecimal(0);//最新价格人民币和今日开盘价格,y用于小数点截取两位小数
        BigDecimal buyM = BigDecimal.ZERO;
        BigDecimal sellM = BigDecimal.ZERO;
        //获取货币，转成map
        List<CurrencyInfo>  allCurrencyInfo = redisCacheComponent.getCurrencyList();
        Map<String,String> currencyInfoMap = new HashMap<>();
        if(allCurrencyInfo != null && allCurrencyInfo.size() > 0){
            for(CurrencyInfo currencyInfo:allCurrencyInfo){
                currencyInfoMap.put(currencyInfo.getSymbol(),currencyInfo.getImageUrl());
            }
        }
        String cmcId = "";
        // 组装数据
        for(ExchangeTransactionpair pair:middleList){
            pair.setIsDepth(pair.getIsDepth()!=null?pair.getIsDepth():0);
            vo = new ApiKActionQuantizationVo();
            kActionTotalPo = new KActionTotalPo();
            //获取24h涨幅、今日涨幅、1h涨幅、最新价格,今日开盘
            //ss = System.currentTimeMillis();
            redisKey = RedisKeysUtils.API_SERVICE_K_ACTION_ALL_DATA_PRICE+"@"+pair.getExchangeId()+"@"+pair.getTransactionName();
            data = rediscConfig.get(redisKey);
           // LogTrace.info("行情k线","获取最新价格数据耗时",String.valueOf(System.currentTimeMillis()- ss));
            vo.setExchangeId(pair.getExchangeId());
            vo.setExchangeName(pair.getExchangeName());
            vo.setTransactionId(pair.getTransactionId());
            vo.setTransactionName(pair.getTransactionName());
            vo.setTimeLong(System.currentTimeMillis());
            cmcId = pair.getTransactionName().split("/")[0];
            vo.setImageUrl(currencyInfoMap.get(cmcId.toUpperCase()));
            //vo.setImageUrl(pair.getImageUrl());
            vo.setMiddleId(pair.getMiddleId());
            vo.setIsDepth(pair.getIsDepth()!=null?pair.getIsDepth():0);
            if(StringUtils.isNotBlank(data)){
                kActionTotalPo =  JSON.parseObject(data,KActionTotalPo.class);
                vo.setChangePrice(StringUtils.isNotBlank(kActionTotalPo.getChangePrice())?Double.valueOf(kActionTotalPo.getChangePrice()):0);
                vo.setChangePrice1H(StringUtils.isNotBlank(kActionTotalPo.getChangePrice1H())?Double.valueOf(kActionTotalPo.getChangePrice1H()):0);
                vo.setChangePriceToday(StringUtils.isNotBlank(kActionTotalPo.getChangePriceToday())?Double.valueOf(kActionTotalPo.getChangePriceToday()):0);
                vo.setChangFlag(kActionTotalPo.getChangFlag()!=null?kActionTotalPo.getChangFlag():0);
                lastPriceB = this.getConverCut(kActionTotalPo.getOpenPriceCny());
                vo.setLastOpenPrice(Double.valueOf(lastPriceB.toString()));
                lastPriceB = this.getConverCut(kActionTotalPo.getTodayOpenPriceCny());
                vo.setOpenPriceCny(Double.valueOf(lastPriceB.toString()));
                //美元价格
                vo.setLastOpenPriceUsd( Double.valueOf( kActionTotalPo.getLastOpenPrice() ) );
                lastPriceB = this.getConverCut(kActionTotalPo.getLastOpenPrice());
                vo.setLastOpenPriceUsdStr(lastPriceB.stripTrailingZeros().toPlainString());
            }
            //获取24h最高、最低价格、昨日收盘价格
            //ss = System.currentTimeMillis();API_SERVICE_TRADES_24H_MAX_MIN_PRICE_VOLUME
            redisKey = RedisKeysUtils.API_SERVICE_TRADES_24H_MAX_MIN_PRICE_VOLUME+"@"+pair.getExchangeId()+"@"+pair.getTransactionName();
            data = rediscConfig.get(redisKey);
            //LogTrace.info("行情k线","获取24h交易量数据耗时",String.valueOf(System.currentTimeMillis()- ss));
            if(StringUtils.isNotBlank(data)){
                kActionTotalPo =  JSON.parseObject(data,KActionTotalPo.class);
                lastPriceB = this.getConverCut(kActionTotalPo.getMaxPrice24H());
                vo.setMaxPrice24H(Double.valueOf(lastPriceB.toString()));
               // vo.setMaxPrice24H(StringUtils.isNotBlank(kActionTotalPo.getMaxPrice24H())?Double.valueOf(kActionTotalPo.getMaxPrice24H()):0);
                lastPriceB = this.getConverCut(kActionTotalPo.getMinPrice24H());
                vo.setMinPrice24H(Double.valueOf(lastPriceB.toString()));
                //vo.setMinPrice24H(StringUtils.isNotBlank(kActionTotalPo.getMinPrice24H())?Double.valueOf(kActionTotalPo.getMinPrice24H()):0);
                //vo.setAmount(StringUtils.isNotBlank(kActionTotalPo.getAmount())?Double.valueOf(kActionTotalPo.getAmount()):0);
                if(null != kActionTotalPo && StringUtils.isNotBlank(kActionTotalPo.getYesterdayClosePriceCny())){
                   // lastPriceB = StringUtils.isNotBlank(kActionTotalPo.getYesterdayClosePriceCny())?new BigDecimal(kActionTotalPo.getYesterdayClosePriceCny()).setScale(2,BigDecimal.ROUND_DOWN):BigDecimal.valueOf(0);
                    lastPriceB = this.getConverCut(kActionTotalPo.getYesterdayClosePriceCny());
                    vo.setYesterdayClosePriceCny(Double.valueOf(lastPriceB.toString()));
                   // vo.setYesterdayClosePriceCny(Double.valueOf(lastPriceB.toString()));
                }
            }
            //获取24小时净流入,24h成交额
            JSONObject jsonObject;
            //ss = System.currentTimeMillis();
            redisKey = RedisKeysUtils.API_SERVICE_TRADES_24H_CAPITAL_FLOW_DATA+"@"+pair.getExchangeId()+"@"+pair.getTransactionName();
            data = rediscConfig.get(redisKey);
            //LogTrace.info("行情k线","获取24小时净流入数据耗时",String.valueOf(System.currentTimeMillis()- ss));
            if(StringUtils.isNotBlank(data)){
                jsonObject = JSON.parseObject(data);
                //today = new ApiCapitalInflowSituationVo();
                //today = JSON.parseObject(JSON.toJSONString(jsonObject.get("today")),ApiCapitalInflowSituationVo.class);
               /* if(today != null && StringUtils.isNotBlank(today.getBuySellAmount())){
                }*/
                today = JSON.parseObject(JSON.toJSONString(jsonObject.get("dayHours")),ApiCapitalInflowSituationVo.class);
                if(today != null && StringUtils.isNotBlank(today.getBuyAmount()) && StringUtils.isNotBlank(today.getSellAmount())){
                    buyM = new BigDecimal(today.getBuyAmount());
                    sellM = new BigDecimal(today.getSellAmount());
                    buyM = buyM.add(sellM);
                    buyM = getConverCut(buyM.toString());
                    // double amount = Double.valueOf(buyM.toString());
                    vo.setAmount(Double.valueOf(buyM.stripTrailingZeros().toPlainString()));
                    vo.setCapitionFlow(Double.valueOf(today.getBuySellAmount()));
                }
            }
            //获取今日开盘 --已经放入API_SERVICE_K_ACTION_CHANGE_PRICE redis中
            //ss = System.currentTimeMillis();
            /*redisKey = RedisKeysUtils.API_SERVICE_TRADES_PRIOD+"@"+pair.getExchangeId()+"@"+pair.getTransactionName()+"@"+redisPriceDate;
            data = rediscConfig.get(redisKey);
            //LogTrace.info("行情k线","获取今日开盘数据耗时",String.valueOf(System.currentTimeMillis()- ss));
            if(StringUtils.isNotBlank(data)){
                TradesHistory tradesHistory = JSON.parseObject(data,TradesHistory.class);
                if(tradesHistory != null && null != tradesHistory.getPrice()){
                    lastPriceB = StringUtils.isNotBlank(tradesHistory.getPriceCny())?new BigDecimal(tradesHistory.getPriceCny()).setScale(2,BigDecimal.ROUND_DOWN):BigDecimal.valueOf(0);
                    vo.setOpenPriceCny(Double.valueOf(lastPriceB.toString()));
                }
            }*/
            //获取昨日收盘 -- 放入24小时最高、最低、24小时成交量rdis中（API_SERVICE_TRADES_24H_MAX_MIN_PRICE_VOLUME）
            //ss = System.currentTimeMillis();
            /*redisKey= RedisKeysUtils.API_SERVICE_TRADES_PRIOD_YESTERDAY+"@"+pair.getExchangeId()+"@"+pair.getTransactionName();
            data= rediscConfig.get(redisKey);
            //LogTrace.info("行情k线","获取昨日收盘数据耗时",String.valueOf(System.currentTimeMillis()- ss));
            if(StringUtils.isNotBlank(data)){
                kActionTotalPo =  JSON.parseObject(data,KActionTotalPo.class);
                if(null != kActionTotalPo && StringUtils.isNotBlank(kActionTotalPo.getYesterdayClosePriceCny())){
                    lastPriceB = StringUtils.isNotBlank(kActionTotalPo.getYesterdayClosePriceCny())?new BigDecimal(kActionTotalPo.getYesterdayClosePriceCny()).setScale(2,BigDecimal.ROUND_DOWN):BigDecimal.valueOf(0);
                    vo.setYesterdayClosePriceCny(Double.valueOf(lastPriceB.toString()));
                }
            }*/
            dataVo.add(vo);
            //单独把当前交易所-交易对放入redis中，自选接口直接获取
            rediscConfig.set(RedisKeysUtils.K_ACTION_SELF_SELECT+"@"+pair.getExchangeId()+"@"+pair.getTransactionName(),JSON.toJSONString(vo));
        }
        LogTrace.info("行情k线-akka","获取所有数据耗时-"+queryExchange,String.valueOf(System.currentTimeMillis()- st));
        return dataVo;
    }

    public static BigDecimal getConverCut(String lastPriceB) {
        BigDecimal result = new BigDecimal(0);
        result = StringUtils.isNotBlank(lastPriceB)?new BigDecimal(lastPriceB).setScale(10,BigDecimal.ROUND_DOWN):result;
        if(result.compareTo(BigDecimal.valueOf(1)) >=0){
            result = result.setScale(2,BigDecimal.ROUND_DOWN);
        }else{
            BigDecimal divisor = BigDecimal.ONE;
            MathContext mc = new MathContext(5);
            result = result.divide(divisor, mc);
        }
        return result;
    }

}
